﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Unis.Framework.Core.Infrastructure
{
    /// <summary>
    /// 作用：用来存储在整个应用程序域生命周期内的单例对象
    /// </summary>
    /// <typeparam name="T">将要存储的类型</typeparam>
    /// <remarks>
    ///作者：王强
    ///时间：2016年11月10日 
    /// </remarks>
    public class Singleton<T> : Singleton 
    {
        static T instance;

        /// <summary>
        ///对于类型T只有一个实例
        ///每一个类型T在同一个时间内，只有一个实例对象 
        /// </summary>
        public static T Instance
        {
            get { return instance; }
            set
            {
                instance = value;
                AllSingletons[typeof(T)] = value;
            }
        }

        public static T InstanceObj
        {
            get { return SingletonCreator<T>.instance; }
        }

        // Nested Types
        private class SingletonCreator<T> 
        {
            // Fields
            internal static readonly T instance;

            // Methods
            static SingletonCreator()
            {
                Singleton<T>.SingletonCreator<T>.instance = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);
            }
        }
    }


    /// <summary>
    /// Provides access to all "singletons" stored by <see cref="Singleton{T}"/>.
    /// </summary>
    public class Singleton
    {
        static Singleton()
        {
            allSingletons = new Dictionary<Type, object>();
        }

        static readonly IDictionary<Type, object> allSingletons;

        /// <summary>Dictionary of type to singleton instances.</summary>
        public static IDictionary<Type, object> AllSingletons
        {
            get { return allSingletons; }
        }
    }


}
